<?php

namespace Thenbsp\Wechat;

use Thenbsp\Wechat\Wechat;
use Thenbsp\Wechat\Util\Util;
use Thenbsp\Wechat\Util\Json;
use Thenbsp\Wechat\Util\SignGenerator;

/**
 * 生成 JSSDK 配置
 * Created by thenbsp (thenbsp@gmail.com)
 * Created at 2015/07/21
 */
class Jssdk
{
    /**
     * jssdk config
     */
    protected $config = array();

    /**
     * 构造方法
     */
    public function __construct(Wechat $wechat)
    {
        $config = array(
            'appId'     => $wechat->getAppid(),
            'nonceStr'  => Util::randomString(),
            'timestamp' => time()
        );

        $signGenerator = new SignGenerator(array(
            'jsapi_ticket'  => $wechat->getTicket(),
            'noncestr'      => $config['nonceStr'],
            'timestamp'     => $config['timestamp'],
            'url'           => Util::currentUrl()
        ));
        $signGenerator->setHashType('sha1');
        $signGenerator->setUpper(false);

        $config['signature'] = $signGenerator->getResult();

        $this->config = $config;
    }

    /**
     * 获取配置文件（json）
     */
    public function getConfig(array $api, $debug = false)
    {
        $this->config['jsApiList']  = $api;

        if( $debug ) {
            $this->config['debug'] = true;
        }

        return Json::encode($this->config);
    }

    /**
     * 获取配置文件（array）
     */
    public function getConfigArray(array $api, $debug = false)
    {
        $this->config['jsApiList'] = $api;

        if( $debug ) {
            $this->config['debug'] = true;
        }

        return $this->config;
    }

}